import React, { Component } from 'react'
/**
 * state版的购物车
 */
export default class App extends Component {
  constructor(){
    super()
    //this.totalPrice=this.totalPrice.bind(this)
    this.state={
      list:[
        {
          id:'1001',
          name:'威化饼干',
          price:6.7,
          count:1
        },
        {
          id:'1002',
          name:'曲奇饼干',
          price:3.7,
          count:1
        },
        {
          id:'1003',
          name:'苏打饼干',
          price:2.7,
          count:1
        }
      ]
    }
  }

  changeNum=(op,id)=>{
    switch(op){
      case '+':
        const newList1=this.state.list.map(item=>{
          if(item.id==id){
            item.count++
          }
          return item;
        })
        this.setState({list:newList1})
        break;
      case '-':
        const newList2=this.state.list.map(item=>{
          if(item.id==id){
            if(item.count==1){
              window.alert('数量不能小于1')
            }else{
              item.count--
            }
           
          }
          return item;
        })
        this.setState({list:newList2})
        break;
    }
  }
  //使用get访问器，来模拟计算属性
  get totalPrice(){
    return `￥${this.state.list.reduce((prev,cur)=>prev+cur.price*cur.count,0).toFixed(2)}`
  }
  //state数据变化的时候会变
  render() {
    console.log('--------render-----');
    //首先要将state内容解构出来
    const {list}=this.state
    //定义变量用来表示表格头部集合的
    let headerList=['编号','名称','价格','数量','小计']
    return (
      <div>
         <table>
            <thead>
               <tr>
                  {headerList.length>0&&headerList.map(item=><td key={item}>{item}</td>)}
               </tr>
            </thead>
            <tbody>
              {
                list.length>0&&list.map(item=><tr key={item.id}>
                  <td>{item.id}</td>
                  <td>{item.name}</td>
                  <td>{item.price}</td>
                  <td>
                    <button onClick={()=>this.changeNum('-',item.id)}>-</button>
                    <span>{item.count}</span>
                    <button onClick={()=>this.changeNum('+',item.id)}>+</button>
                  </td>
                  <td>{(item.price*item.count).toFixed(2)}</td>
                </tr>) 
              }
            </tbody>
            <tfoot>
              <tr>
                <td colSpan={5}>{this.totalPrice}</td>
              </tr>
            </tfoot>

         </table>
      </div>
    )
  }
}
